//
//  NMPOManager.swift
//  NMPO
//
//  Created by PowerfullClean on 2023/10/25.
//

import UIKit
import NetworkExtension
import CoreLocation
import Alamofire
import CoreData
@objc protocol NMPOManagerDelegate: NSObjectProtocol {
    @objc optional func nmpo_iPScanFinish(nmpo_model: NMPOIPScanModel?)
    @objc optional  func nmpo_downloadFinish(nmpo_value: String)
    @objc optional func nmpo_upLoadFinish(nmpo_value: String)
    @objc optional func nmpo_pingFinish(nmpo_ping: String, nmpo_jitter: String, nmpo_loss: String)
}
class NMPOManager: NSObject {
    @objc static let nmpo_manager = NMPOManager()
    override init() {
        super.init()
        
        nmpo_addVPNChangeNoti()
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(nmpo_enterActive),
            name: UIApplication.didBecomeActiveNotification, object: nil)
        
        nmpo_pathMonitor.start(queue: DispatchQueue.global())
        nmpo_pathMonitor.pathUpdateHandler = { path in
            DispatchQueue.main.async {
                if path.status == .satisfied {
                    if path.usesInterfaceType(.wifi) {
                        self.nmpo_netType = .nmpo_wifi
                    } else if path.usesInterfaceType(.cellular) {
                        
                        self.nmpo_netType = .nmpo_cellular
                    }
                } else {
                    self.nmpo_netType = .nmpo_none
                    NMPOHudVender.nmpo_showMessage("No available network", isError: false)
                }
            }
        }
    }
    //MARK: - nmpo save key
    @objc func nmpo_saveIntKey(nmpo_key: String, nmpo_value: NSInteger, nmpo_timeID: String = "") {
        UserDefaults.standard.setValue(nmpo_value, forKey: nmpo_key+nmpo_timeID)
        UserDefaults.standard.synchronize()
    }
    @objc func nmpo_getIntValue(nmpo_key: String, nmpo_timeID: String = "") -> NSInteger {
        guard let nmpo_value =  UserDefaults.standard.value(forKey: nmpo_key+nmpo_timeID) as? NSInteger else { return 0 }
        return nmpo_value
    }
    
    @objc func nmpo_saveSrKey(nmpo_key: String, nmpo_value: String, nmpo_timeID: String = "") {
        UserDefaults.standard.setValue(nmpo_value, forKey: nmpo_key+nmpo_timeID)
        UserDefaults.standard.synchronize()
    }
    @objc func nmpo_getSrValue(nmpo_key: String, nmpo_timeID: String = "") -> String {
        guard let nmpo_value =  UserDefaults.standard.value(forKey: nmpo_key+nmpo_timeID) as? String else { return "" }
        return nmpo_value
    }
    //MARK: - nmpo setting
    func nmpo_switchAppStore()  {
        let nmpo_urlString = "itms-apps://itunes.apple.com/cn/app/id\(nmpo_appID)?mt=8&action=write-review"
        let url = URL(string: nmpo_urlString)
        if #available(iOS 10, *) {
            UIApplication.shared.open(url!, options: [:],
                                      completionHandler: {
                (success) in
            })
        } else {
            UIApplication.shared.openURL(url!)
        }
    }
    func nmpo_shareApp(nmpo_vc: NMPOBaseViewController?) {
        var activityItems:[Any]?
        let url = URL(string: "https://itunes.apple.com/app/id\(nmpo_appID)")
        activityItems = ["Martian Proxy", url!]
        let nmpo_activity = UIActivityViewController(activityItems: activityItems!, applicationActivities: nil)
        nmpo_activity.excludedActivityTypes = [.saveToCameraRoll, .openInIBooks, .addToReadingList]
        nmpo_activity.completionWithItemsHandler = { a, c, r, e in
        }
        nmpo_vc?.present(nmpo_activity, animated: true)
    }
    //MARK: - nmpo lazy
    var nmpo_netType: NMPONetType = .nmpo_none
    let nmpo_pathMonitor = NWPathMonitor()
    let nmpo_appID = "6470997571"
    var nmpo_loctionManager = CLLocationManager()
    weak var nmpo_delegate:NMPOManagerDelegate?
    var nmpo_initEntry = true //程序冷启动
    let nmpo_storeManager =  NSPersistentContainer(name: "NMPODataBaseModel")
    //MARK: - nmpo speed test
    var nmpo_pingErr = false
    var nmpo_pingobjct: NMPOSwiftyPingVender?
    var nmpo_stopDownloadRequest = false
    var nmpo_stopUploadRequest = false
    var nmpo_downloadRequest:DownloadRequest?
    var nmpo_uploadRequest:UploadRequest?
    var nmpo_downAddNumber = 0
    var nmpo_downloadName: String = "nmpo_downloadName"
    var nmpo_uploadAddNumber = 0
    var nmpo_uploadName: String = "nmpo_uploadName"
    var nmpo_downloadValue: Double = 0
    var nmpo_uploadValue: Double = 0
    var nmpo_homeDownloadValue: Double = 0
    var nmpo_homeUploadValue: Double = 0
    var nmpo_speedType = 0
    var nmpo_funcInModel: NMPOIPScanModel?
    //MARK: - nmpo vpn
    var nmpo_vpnStateClickType: NMPOVPNStateClickType = .nmpo_none
    var nmpo_vpnCurStateType: NMPOVpnStateType {
        return NMPOVpnStateType(rawValue: nmpo_vpnManager?.connection.status.rawValue ?? 0) ?? .nmpo_disconnected
    }
    var nmpo_curServerModel: NMPOSerModel?
    var nmpo_vpnManager:NETunnelProviderManager?
    var nmpo_vpnChangeBlock: ((NMPOVpnStateType)->())?
    let pingGroup1 = DispatchGroup()
    let pingQueue1 = DispatchQueue(label: "com.marksproxy.pingqueue1")
    let pingGroup2 = DispatchGroup()
    let pingQueue2 = DispatchQueue(label: "com.marksproxy.pingqueue2")
    var nmpo_best: Bool = false
    var nmpo_smart: Bool = false
}
//MARK: - nmpo 后台
extension NMPOManager {
    @objc func nmpo_enterActive() {
        if (nmpo_vpnCurStateType == .nmpo_invalid || nmpo_vpnCurStateType == .nmpo_disconnected) {
            nmpo_vpnChangeBlock?(.nmpo_invalid)
        }
        
    }
}
